package com.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class HiveUtils {
    private static Properties properties = ProUtils.getProperties();
    private static String JDBC_DRIVER = "org.apache.hive.jdbc.HiveDriver";
    private static String CONNECTION_URL ;

    static {
        System.setProperty("HADOOP_USER_NAME",properties.getProperty("hadoop.user"));
        CONNECTION_URL=properties.getProperty("jdbc.url");
        try {
            Class.forName(JDBC_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Connection getHiveConn(){
        //登录Kerberos账号
        System.setProperty("java.security.krb5.conf", properties.getProperty("kerb5.file"));
        Configuration configuration = new Configuration();
        configuration.set("hadoop.security.authentication" , "Kerberos" );
        UserGroupInformation.setConfiguration(configuration);
        try {
            UserGroupInformation.loginUserFromKeytab(properties.getProperty("hive.principal") ,
                    properties.getProperty("hive.keytab.file"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        Connection connection = null;
        if (connection!=null) {
                return connection;
        }
        try {
            connection= DriverManager.getConnection(CONNECTION_URL);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}